﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// GameEventSystem
///
///
/// Regist -> Raise -> Handler
///
///
/// </summary>

namespace TTGameEngine {

public enum GameEventID {
    GE_NoInit = 0,
    GE_StartGame,
    GE_EnterRoom,
    GE_ExitRoom,
    GE_EnterBattle,
    GE_ExitBattle,
}

public delegate void EventHandler(GameEvent e);

public class GameEvent {
    public GameEventID m_eventID = GameEventID.GE_NoInit;
    public object[] m_args;
    public GameEvent(GameEventID eventID, object[] args)
    {
        m_eventID = eventID;
        m_args = args;
    }
}

public class TTEventSystem : SingletonMono<TTEventSystem> {

//         static EventSystem m_instance;
//
//         public static EventSystem Ins {
//             get {
//                 if (m_instance == null) {
//                     m_instance = GameLauncher.Self.AddLogicScript<EventSystem>();
//                 }
//                 return m_instance;
//             }
//         }

    List<GameEvent> m_events = new List<GameEvent>();
    Dictionary<GameEventID, EventHandler> m_eventHandlers = new Dictionary<GameEventID, EventHandler>();

    // Use this for initialization
    void Start() {


    }

    public void RaiseEvent(GameEventID eventID, params object[] args) {
        DebugUtil.LogFormat("[EventSys] RaiseEvent...[{0}]", eventID.ToString());
        handlerEvent(new GameEvent(eventID, args));
    }

    public void RegistEventHandler(GameEventID eventID, EventHandler handler) {
        DebugUtil.LogFormat("[EventSys] RegistEvent...[{0}] handler[{1}]", eventID.ToString(), handler.ToString());
        EventHandler handlerDele = null;
        if(m_eventHandlers.TryGetValue(eventID, out handlerDele)) {
            handlerDele += handler;
        } else {
            m_eventHandlers.Add(eventID, handler);
        }

    }

    // Update is called once per frame
//     void Update() {
//         if(m_events.Count > 0) {
//             for(int i = 0; i < m_events.Count; i++) {
//                 handlerEvent(m_events[i]);
//             }
//             m_events.Clear();
//         }
//     }

    void handlerEvent(GameEvent e) {
        EventHandler handler = null;
        if(m_eventHandlers.TryGetValue(e.m_eventID, out handler)) {
            DebugUtil.LogFormat("[EventSys] HandleEvent...[{0}]  handle[{1}]", e.m_eventID.ToString(), handler.ToString());
            handler(e);
        }

    }

}
}